/**
 * 语音管理模块
 * 使用 Web Speech API 实现文字转语音
 */

class SpeechManager {
    constructor() {
        this.synthesis = window.speechSynthesis;
        this.currentUtterance = null;
        this.rate = 1.0; // 语速
        this.voices = [];
        
        this.init();
    }

    init() {
        if (!this.synthesis) {
            console.error('浏览器不支持 Web Speech API');
            return;
        }

        // 加载可用的语音
        this.loadVoices();
        
        // 语音列表可能异步加载
        if (this.synthesis.onvoiceschanged !== undefined) {
            this.synthesis.onvoiceschanged = () => {
                this.loadVoices();
            };
        }

        console.log('🔊 语音管理器初始化完成');
    }

    /**
     * 加载可用语音
     */
    loadVoices() {
        this.voices = this.synthesis.getVoices();
        console.log(`找到 ${this.voices.length} 个语音`);
    }

    /**
     * 获取英语语音
     */
    getEnglishVoice() {
        // 优先选择美式英语
        let voice = this.voices.find(v => v.lang === 'en-US');
        
        // 如果没有，选择任意英语语音
        if (!voice) {
            voice = this.voices.find(v => v.lang.startsWith('en'));
        }

        return voice;
    }

    /**
     * 播放单词（完整）
     */
    speak(text) {
        return new Promise((resolve, reject) => {
            if (!this.synthesis) {
                console.error('语音合成不可用');
                reject(new Error('语音合成不可用'));
                return;
            }

            console.log('🔊 播放:', text);

            // 停止当前播放
            this.stop();

            const utterance = new SpeechSynthesisUtterance(text);
            utterance.lang = 'en-US';
            utterance.rate = this.rate;
            
            // 重新加载语音列表（某些浏览器需要）
            if (this.voices.length === 0) {
                this.voices = this.synthesis.getVoices();
            }
            
            const voice = this.getEnglishVoice();
            if (voice) {
                utterance.voice = voice;
                console.log('使用语音:', voice.name);
            }

            utterance.onend = () => {
                console.log('✅ 播放完成');
                resolve();
            };

            utterance.onerror = (error) => {
                console.error('❌ 语音播放错误:', error);
                reject(error);
            };

            this.currentUtterance = utterance;
            this.synthesis.speak(utterance);
            
            console.log('开始播放...');
        });
    }

    /**
     * 播放驼峰命名（分词）
     */
    async speakCamelCase(text, gap = 600) {
        const words = this.splitCamelCase(text);
        
        for (let i = 0; i < words.length; i++) {
            await this.speak(words[i]);
            
            // 如果不是最后一个词，等待间隔
            if (i < words.length - 1) {
                await this.delay(gap);
            }
        }
    }

    /**
     * 拆分驼峰命名
     */
    splitCamelCase(text) {
        // getUserName → ["get", "User", "Name"]
        const parts = text.split(/(?=[A-Z])/);
        // 转小写 → ["get", "user", "name"]
        return parts.map(p => p.toLowerCase());
    }

    /**
     * 延迟
     */
    delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    /**
     * 停止播放
     */
    stop() {
        if (this.synthesis.speaking) {
            this.synthesis.cancel();
        }
    }

    /**
     * 设置语速
     */
    setRate(rate) {
        this.rate = Math.max(0.5, Math.min(2.0, rate));
    }

    /**
     * 获取当前语速
     */
    getRate() {
        return this.rate;
    }

    /**
     * 是否正在播放
     */
    isSpeaking() {
        return this.synthesis.speaking;
    }
}

// 全局实例
let speechManager;

// 确保在 DOM 加载后初始化
if (typeof window !== 'undefined') {
    speechManager = new SpeechManager();
    window.speechManager = speechManager;
    console.log('✅ speechManager 已挂载到 window');
}

